<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Log;

class GenerateInterfaceAndImpl extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('make:generateInterfaceAndImpl')
            ->addArgument('name', Argument::REQUIRED, 'Service name (e.g., RoleService)')
            ->addOption('force', 'f', Option::VALUE_NONE, 'Overwrite existing files')
            ->setDescription('Create a new service interface and implementation');
    }

    protected function execute(Input $input, Output $output)
    {
        $name = $input->getArgument('name');
        $force = $input->getOption('force');

        // 确保名称以Service结尾
        if (!str_ends_with($name, 'Service')) {
            $name .= 'Service';
        }

        $implName = $name . 'Impl';

        try {
            // 创建接口
            $this->createFromStub($name, 'interface.stub', 'service', $name, [], $force);
            // 创建实现类
            $this->createFromStub($implName, 'interfaceImpl.stub', 'service/impl', $implName, [
                '{InterfaceName}' => $name,
            ], $force);

            $output->writeln('<info>Service created successfully:</info>');
            $output->writeln("Interface: app/service/{$name}.php");
            $output->writeln("Implementation: app/service/impl/{$implName}.php");

        } catch (\Exception $e) {
            $output->writeln('<error>Failed to create service: ' . $e->getMessage() . '</error>');
            return 1;
        }

        return 0;
    }

    protected function createFromStub(
        string $className,
        string $stubFile,
        string $subDir,
        string $fileName,
        array $additionalReplacements = [],
        bool $force = false
    ): void {
        $stubPath = $this->app->getConfigPath() . 'stubs' . DIRECTORY_SEPARATOR . $stubFile;

        if (!file_exists($stubPath)) {
            throw new \RuntimeException("Stub file not found: {$stubPath}");
        }

        $content = file_get_contents($stubPath);

        // 基础替换
        $replacements = array_merge([
            '{InterfaceName}' => $className,
            '{InterfaceImplName}' => $className
        ], $additionalReplacements);

        // 执行替换
        $content = str_replace(
            array_keys($replacements),
            array_values($replacements),
            $content
        );

        $filePath = $this->app->getBasePath() . $subDir . DIRECTORY_SEPARATOR . $fileName . '.php';

        // 确保目录存在
        $fileDir = dirname($filePath);
        if (!is_dir($fileDir)) {
            mkdir($fileDir, 0755, true);
        }

        if (file_exists($filePath) && !$force) {
            throw new \RuntimeException("File {$fileName} already exists! Use --force to overwrite.");
        }

        file_put_contents($filePath, $content);
    }

}
